package com.example.demo.Filter;

import com.example.demo.Utils.JwtTokenUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Component
public class JwtTokenFilter extends OncePerRequestFilter {

    @Value("${jwt.tokenHeader}")
    private String JWT_TOKENHEADER;

    @Value("${jwt.tokenHead}")
    private String JWT_TOKENHEAD;

    @Autowired
    JwtTokenUtil jwtTokenUtil;

    @Override
    protected void doFilterInternal(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, FilterChain filterChain) throws ServletException, IOException {
        httpServletResponse.setHeader("Access-Control-Allow-Origin", "*");
        httpServletResponse.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE");
        httpServletResponse.setHeader("Access-Control-Max-Age", "3600");
        httpServletResponse.setHeader("Access-Control-Allow-Headers", "*");
        httpServletResponse.setHeader("Access-Control-Request-Headers", "Authorization,Origin, X-Requested-With,content-Type,Accept");
        httpServletResponse.setHeader("Access-Control-Expose-Headers", "*");
        if(httpServletRequest.getMethod().toUpperCase().equals("OPTIONS")){
            httpServletResponse.setStatus(HttpStatus.OK.value());
            return;
        }
        if ("/getAllCourse".equals(httpServletRequest.getRequestURI())||"/loginOfStudent".equals(httpServletRequest.getRequestURI())
                ||"/captcha".equals(httpServletRequest.getRequestURI())||"/loginOfTeacher".equals(httpServletRequest.getRequestURI())) {
            filterChain.doFilter(httpServletRequest, httpServletResponse);
        } else{
//            Result result = null;
//            String tokenHeader = httpServletRequest.getHeader(JWT_TOKENHEADER);
//            String token = null;
//        if (tokenHeader != null) {
//            token = tokenHeader.substring(JWT_TOKENHEAD.length());
//            if (jwtTokenUtil.isExpiration(token)) {
//                result = new Result(403, "token已过期，请重新登录!");
//            }
//        } else {
//           // result = new Result(403, "未获取到token，请登录!");
//        }
//           if(result!=null) {
//               PrintWriter writer = new PrintWriter(new OutputStreamWriter(httpServletResponse.getOutputStream()));
//               writer.write(new ObjectMapper().writeValueAsString(result));
//               writer.flush();
//               writer.close();
//           }

        filterChain.doFilter(httpServletRequest, httpServletResponse);
        }
    }


}
